<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师信息管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="咨询师名称">
			<el-input v-model="queryInfo.counselorName" placeholder="请输入咨询师名称" clearable @clear="queryDataList" />
		</el-form-item>

		<el-form-item label="咨询师等级">
			<el-select v-model="queryInfo.counselorGradeId" placeholder="请选择咨询师等级" clearable @clear="queryDataList">
				<el-option v-for="item in counselorGradeOptions" :key="item.value" :label="item.label"
					:value="item.value" />
			</el-select>
		</el-form-item>

		<el-form-item label="手机号">
			<el-input v-model="queryInfo.mobile" placeholder="请输入手机号" clearable @clear="queryDataList" />
		</el-form-item>

		<el-form-item label="地址">
			<el-input v-model="queryInfo.address" placeholder="请输入地址" clearable @clear="queryDataList" />
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="primary" @click="add">新增</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column type="selection" fixed="left" width="40" />
		<el-table-column property="id" label="ID" fixed="left" width="50" />
		<el-table-column property="counselorName" label="咨询师名称" />
		<el-table-column property="counselorGrade.gradeName" label="咨询师等级" />
		<el-table-column property="mobile" label="手机号" />
		<el-table-column property="email" label="邮箱" />
		<el-table-column property="headImageUrl" label="头像">
			<template #default="scope">
				<el-avatar shape="square" size="large" :src="'http://localhost:8080' + scope.row.headImageUrl" />
			</template>
		</el-table-column>

		<el-table-column property="certificateUrl" label="资格证书">
			<template #default="scope">
				<el-avatar shape="square" size="large" :src="'http://localhost:8080' + scope.row.certificateUrl" />
			</template>
		</el-table-column>

		<!-- 修改后的性别列 -->
		<el-table-column label="性别" width="60">
			<template #default="scope">
				{{ scope.row.sex === 0 ? '男' : '女' }}
			</template>
		</el-table-column>

		<el-table-column property="address" label="地址" />
		<el-table-column property="intro" label="简介" />
		<el-table-column property="post" label="职位">
			<template #default="scope">
				<el-tag type="primary" size="large" v-if="scope.row.post === 0">咨询师</el-tag>
				<el-tag type="danger" size="large" v-else>心理导师</el-tag>
			</template>
		</el-table-column>

		<el-table-column fixed="right" label="操作" min-width="110">
			<template #default='scope'>
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" size="default" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<!-- 新增和修改对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="counselorData" label-width="100px">
			<el-form-item label="咨询师名称">
				<el-input v-model="counselorData.counselorName" autocomplete="off" placeholder="请输入咨询师名称"></el-input>
			</el-form-item>
			<el-form-item label="咨询师等级">
				<el-select v-model="counselorData.counselorGradeId" placeholder="请选择咨询师等级">
					<el-option v-for="item in counselorGradeOptions" :key="item.value" :label="item.label"
						:value="item.value" />
				</el-select>
			</el-form-item>

			<el-form-item label="手机号">
				<el-input v-model="counselorData.mobile" placeholder="请输入手机号"></el-input>
			</el-form-item>

			<el-form-item label="邮箱">
				<el-input v-model="counselorData.email" placeholder="请输入邮箱"></el-input>
			</el-form-item>

			<!-- 头像上传 -->
			<el-form-item label="头像">
				<el-upload action="http://localhost:8080/upload" list-type="picture-card"
					:on-success="(resp) => handleSuccess(resp, 'head')" :limit="1"
					:on-preview="handlePictureCardPreview" :file-list="headImageList"
					:on-remove="() => handleRemove('head')">
					<el-icon
						style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>

			<!-- 证书图片上传 -->
			<el-form-item label="证书图片">
				<el-upload action="http://localhost:8080/upload" list-type="picture-card"
					:on-success="(resp) => handleSuccess(resp, 'cert')" :limit="1"
					:on-preview="handlePictureCardPreview" :file-list="certificateList"
					:on-remove="() => handleRemove('cert')">
					<el-icon
						style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>

			<!-- 性别选择 -->
			<el-form-item label="性别">
				<el-radio-group v-model="counselorData.sex">
					<el-radio :label="0">男</el-radio>
					<el-radio :label="1">女</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item label="擅长领域">
				<div class="m-4">
					<el-select v-model="selectedTalentIds" multiple collapse-tags collapse-tags-tooltip
						:max-collapse-tags="3" placeholder="请选择擅长领域" style="width: 100%" :max="3">
						<el-option v-for="item in talentOptions" :key="item.value" :label="item.label"
							:value="item.value" />
					</el-select>
				</div>
			</el-form-item>

			<el-form-item label="所属地址">
				<el-input v-model="counselorData.address" placeholder="请输入所属地址"></el-input>
			</el-form-item>

			<el-form-item label="咨询师简介">
				<el-input v-model="counselorData.intro" placeholder="请输入咨询师简介" type="textarea" rows="4"></el-input>
			</el-form-item>

			<el-form-item label="咨询师分类">
				<el-select v-model="counselorData.post" placeholder="请选择咨询师分类">
					<el-option label="咨询师" value=0 />
					<el-option label="心理导师" value=1 />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>

	<!-- 图片预览对话框 -->
	<el-dialog v-model="dialogVisible" title="图片预览">
		<template #content>
			<img w-full :src="dialogImageUrl" alt="Preview Image" />
		</template>
		<template #footer>
			<el-button @click="dialogVisible = false">关闭</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
	import { Plus } from '@element-plus/icons-vue'
	import type { UploadUserFile } from 'element-plus'

	interface Counselor {
		id ?: number;
		counselorName : string;
		counselorGradeId ?: number;
		mobile : string;
		email : string;
		headImageUrl ?: string;
		sex : 0 | 1;
		certificateUrl ?: string;
		address : string;
		intro : string;
		post : 0 | 1;
		del ?: 0 | 1;
	}

	interface CounselorGrade {
		id ?: number;
		gradeName : string;
		del ?: 0 | 1;
	}

	interface GradeOption {
		label : string;
		value : number;
	}

	interface TalentOption {
		label : string;
		value : number;
	}

	interface Talent {
		id ?: number;
		talentName : string;
	}

	// 获取全局axios
	const axios = getCurrentInstance().appContext.config.globalProperties.axios

	// 查询参数
	const queryInfo = reactive({
		counselorName: '',       // 咨询师名称
		counselorGradeId: '',    // 咨询师等级ID（关联counselor_grade表）
		mobile: '',              // 手机号
		address: '',             // 地址
		pageNum: 1,              // 页码
		pageSize: 5              // 每页条数
	})

	// 总数据量
	const total = ref(0)
	// 表格数据列表
	const dataList = ref([])
	// 批量选择的ID列表
	const multipleSelection = ref<number[]>([])
	// 对话框标题
	const title = ref('')
	// 对话框显示状态
	const dialogFormVisible = ref(false)
	// 图片预览对话框显示状态
	const dialogVisible = ref(false)
	// 预览图片URL
	const dialogImageUrl = ref('')
	// 表单数据：与后端Counselor实体字段一一对应
	const counselorData = ref<Counselor>({
		id: 0,
		counselorName: "",
		counselorGradeId: undefined,
		mobile: "",
		email: "",
		headImageUrl: "",
		certificateUrl: "",
		sex: 0,
		address: '',
		intro: "",
		post: 0
	})



	const talentOptions = ref<TalentOption[]>([]);
	const selectedTalentIds = ref<number[]>([]);
	const getTalentList = () => {
		axios.get('/talent')
			.then(resp => {
				if (resp.code === 200) {
					talentOptions.value = resp.data.map((item : Talent) => ({
						label: item.talentName,
						value: item.id as number
					}));
				}
			})
			.catch(error => {
				console.error('获取擅长领域失败:', error);
			});
	};

	// 头像上传文件列表
	const headImageList = ref<UploadUserFile[]>([])
	// 证书上传文件列表
	const certificateList = ref<UploadUserFile[]>([])

	// 新增：咨询师等级选项
	const counselorGradeOptions = ref<GradeOption[]>([])

	// 查询数据列表
	const queryDataList = () => {
		console.log('查询参数:', queryInfo)
		axios.get('/counselor/page', {
			params: queryInfo
		}).then((resp) => {
			console.log('获取咨询师列表数据:', resp)
			if (resp.code === 200) {
				dataList.value = resp.data.list;
				total.value = resp.data.total;
			} else {
				ElMessage.error('数据查询失败：' + resp.msg)
			}
		}).catch((error) => {
			ElMessage.error('网络请求异常：' + error.message)
		})
	}

	// 获取咨询师等级列表
	const getCounselorGrades = () => {
		console.log('获取咨询师等级列表')
		axios.get('/counselorGrade')
			.then((resp) => {
				console.log('获取咨询师等级数据:', resp)
				if (resp.code === 200) {
					// 将后端数据转换为下拉框选项格式
					counselorGradeOptions.value = resp.data.map((item : CounselorGrade) => ({
						label: item.gradeName,
						value: item.id
					}))
				} else {
					ElMessage.error('获取咨询师等级失败：' + resp.msg)
				}
			}).catch((error) => {
				ElMessage.error('获取咨询师等级请求失败：' + error.message)
			})
	}

	// 页面加载时查询数据
	onMounted(() => {
		// 先获取等级列表，再查询数据
		getCounselorGrades()
		queryDataList()
		getTalentList()
	})

	// 处理表格选择变化
	const handleSelectionChange = (val : any[]) => {
		multipleSelection.value = val.map(item => item.id)
	}

	// 分页大小变化
	const handleSizeChange = (size : number) => {
		queryInfo.pageSize = size;
		queryDataList()
	}

	// 页码变化
	const handleCurrentChange = (page : number) => {
		queryInfo.pageNum = page;
		queryDataList()
	}

	// 取消操作（重置表单）
	const cancle = () => {
		counselorData.value = {
			id: 0,
			counselorName: "",
			counselorGradeId: undefined,
			mobile: "",
			email: "",
			headImageUrl: "",
			certificateUrl: "",
			sex: 0,
			address: '',
			intro: "",
			post: undefined
		};
		headImageList.value = [];
		certificateList.value = [];
		selectedTalentIds.value = [];
		dialogFormVisible.value = false;
	}

	const confirm = () => {
	  if (!counselorData.value.counselorName) {
	    ElMessage.warning('请输入咨询师名称');
	    return;
	  }
	  if (!counselorData.value.mobile) {
	    ElMessage.warning('请输入手机号');
	    return;
	  }
	
	  // 2. 擅长领域校验（最多3个 ）
	  if (selectedTalentIds.value.length > 3) {
	    ElMessage.warning('最多只能选择3个擅长领域');
	    return;
	  }
	  if (counselorData.value.id) {
	    axios.put('/counselor', counselorData.value)
	     .then((resp) => {
	        if (resp.code === 200) {
	          const counselorId = counselorData.value.id;
	          return axios.delete(`/counselorTalent/byCounselor/${counselorId}`); 
	        } else {
	          throw new Error('更新咨询师主表失败：' + resp.msg);
	        }
	      })
	     .then(() => {
	        if (selectedTalentIds.value.length > 0) {
	          const relations = selectedTalentIds.value.map(talentId => ({
	            counselorId: counselorData.value.id,
	            talentId: talentId
	          }));
	          return axios.post('/counselorTalent/batch', relations);
	        }
	        return { code: 200 }; 
	      })
	     .then((batchResp) => {
	        if (batchResp.code === 200) {
	          ElMessage.success('编辑成功');
	          cancle();
	          queryDataList();
	        } else {
	          ElMessage.error('更新擅长领域失败：' + batchResp.msg);
	        }
	      })
	     .catch((error) => {
	        ElMessage.error('编辑请求失败：' + error.message);
	      });
	  } else {
	    // 新增操作：直接新增主表 → 再新增关联（如果有选择）
	    axios.post('/counselor', counselorData.value)
	     .then((resp) => {
	        if (resp.code === 200) {
	          const counselorId = resp.data.id;
	          if (selectedTalentIds.value.length > 0) {
	            const relations = selectedTalentIds.value.map(talentId => ({
	              counselorId: counselorId,
	              talentId: talentId
	            }));
	            return axios.post('/counselorTalent/batch', relations);
	          }
	          return { code: 200 };
	        } else {
	          throw new Error('新增咨询师失败：' + resp.msg);
	        }
	      })
	     .then((batchResp) => {
	        if (batchResp.code === 200) {
	          ElMessage.success('新增成功');
	          cancle();
	          queryDataList();
	        } else {
	          ElMessage.error('新增擅长领域失败：' + batchResp.msg);
	        }
	      })
	     .catch((error) => {
	        ElMessage.error('新增请求失败：' + error.message);
	      });
	  }
	};

	// 打开新增对话框
	const add = () => {
		title.value = '新增咨询师';
		cancle(); 
		dialogFormVisible.value = true;
	}

	const edit = (row: any) => {
	  try {
	    console.log('编辑数据:', row);
	    title.value = '编辑咨询师';
	    const counselorId = row.id;
	    axios.get(`/counselor/${counselorId}`)
	      .then(resp => {
	        if (resp.code === 200) {
	          const counselorDetail = resp.data; 
	
	          
	          counselorData.value = {
	            id: counselorDetail.id || 0,
	            counselorName: counselorDetail.counselorName || "",
	            counselorGradeId: counselorDetail.counselorGradeId || 0,
	            mobile: counselorDetail.mobile || "",
	            email: counselorDetail.email || "",
	            headImageUrl: counselorDetail.headImageUrl || "",
	            sex: counselorDetail.sex || 0,
	            certificateUrl: counselorDetail.certificateUrl || "",
	            address: counselorDetail.address || '',
	            intro: counselorDetail.intro || "",
	            post: counselorDetail.post || 0
	          };
	
	          headImageList.value = [];
	          if (counselorDetail.headImageUrl) {
	            const url = counselorDetail.headImageUrl.startsWith('/') 
	              ? counselorDetail.headImageUrl 
	              : '/' + counselorDetail.headImageUrl;
	            headImageList.value = [{
	              name: counselorDetail.headImageUrl.split('/').pop() || 'avatar.jpg',
	              url: 'http://localhost:8080' + url
	            } as UploadUserFile];
	          }
	
	          certificateList.value = [];
	          if (counselorDetail.certificateUrl) {
	            const url = counselorDetail.certificateUrl.startsWith('/') 
	              ? counselorDetail.certificateUrl 
	              : '/' + counselorDetail.certificateUrl;
	            certificateList.value = [{
	              name: counselorDetail.certificateUrl.split('/').pop() || 'certificate.jpg',
	              url: 'http://localhost:8080' + url
	            } as UploadUserFile];
	          }
	
	          if (counselorDetail.counselorTalents && counselorDetail.counselorTalents.length > 0) {
	            selectedTalentIds.value = counselorDetail.counselorTalents.map(
	              (item: any) => item.talentId
	            );
	          } else {
	            selectedTalentIds.value = []; 
	          }
	
	          // 5. 显示对话框
	          dialogFormVisible.value = true;
	        } else {
	          ElMessage.error('获取咨询师详情失败：' + resp.msg);
	        }
	      })
	      .catch(error => {
	        console.error('查询咨询师详情失败:', error);
	        ElMessage.error('加载编辑数据失败，请重试');
	      });
	  } catch (error) {
	    console.error('编辑时出错:', error);
	    ElMessage.error('加载编辑数据失败: ' + (error as Error).message);
	  }
	};

	// 图片上传成功回调
	const handleSuccess = (resp : any, uploadType : 'head' | 'cert') => {
		console.log('上传成功:', resp)
		if (resp.code === 200) {
			if (uploadType === 'head') {
				// 头像上传成功，赋值给 counselorData 的 headImageUrl
				counselorData.value.headImageUrl = resp.data;
				// 更新上传列表
				headImageList.value = [{
					name: resp.data.split('/').pop() || 'avatar.jpg',
					url: 'http://localhost:8080' + resp.data
				} as UploadUserFile];
			} else {
				counselorData.value.certificateUrl = resp.data;
				certificateList.value = [{
					name: resp.data.split('/').pop() || 'certificate.jpg',
					url: 'http://localhost:8080' + resp.data
				} as UploadUserFile];
			}
		} else {
			ElMessage.error('上传失败: ' + resp.msg);
		}
	};

	// 图片移除回调
	const handleRemove = (uploadType : 'head' | 'cert') => {
		if (uploadType === 'head') {
			counselorData.value.headImageUrl = '';
			headImageList.value = [];
		} else {
			counselorData.value.certificateUrl = '';
			certificateList.value = [];
		}
	};

	// 图片预览回调
	const handlePictureCardPreview = (file : UploadUserFile) => {
		dialogImageUrl.value = file.url as string;
		dialogVisible.value = true;
	};

	// 单个删除
	const remove = (id : number) => {
		ElMessageBox.confirm(
			'此操作将删除该咨询师数据，是否继续？',
			'确认删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete(`/counselor/${id}`)
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('删除成功');
						queryDataList();
					} else {
						ElMessage.error('删除失败：' + resp.msg);
					}
				}).catch((error) => {
					ElMessage.error('删除请求失败：' + error.message);
				})
		}).catch(() => {
			ElMessage.info('已取消删除');
		})
	}

	// 批量删除
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择需要删除的数据');
			return;
		}
		ElMessageBox.confirm(
			`此操作将删除选中的${multipleSelection.value.length}条数据，是否继续？`,
			'批量删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete('/counselor', {
				params: { ids: multipleSelection.value.join(',') }
			}).then((resp) => {
				if (resp.code === 200) {
					ElMessage.success('批量删除成功');
					queryDataList();
				} else {
					ElMessage.error('批量删除失败：' + resp.msg);
				}
			}).catch((error) => {
				ElMessage.error('批量删除请求失败：' + error.message);
			})
		}).catch(() => {
			ElMessage.info('已取消删除');
		})
	}
</script>

<style scoped>
	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding: 15px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline {
		padding: 5px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline .el-input,
	.demo-form-inline .el-select {
		width: 175px;
		margin-right: 5px;
	}

	.el-table {
		margin-bottom: 20px;
	}

	.el-pagination {
		text-align: right;
		margin-top: 15px;
	}

	.dialog-footer {
		text-align: right;
	}

	/* 适配textarea高度 */
	.el-textarea {
		width: 100%;
	}
</style>